package soar.template.springboot.mq.rabbitmq.consumer.configuration.mysql;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import soar.template.springboot.mq.rabbitmq.consumer.appconfig.AppConfig;
import soar.template.springboot.mq.rabbitmq.consumer.appconfig.mysql.Config;

@Configuration
class MyMySQLConfiguration
{
    @Resource(name = "appconfig")
    private AppConfig appconfig;

    @Bean(name = "mainDatasource")
    @Primary
    public DataSource mainDatasource() throws Exception
    {
        return create_datasource(appconfig.mysql.main);
    }

    @Bean(name = "mainEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean mainEntityManagerFactory() throws Exception
    {
        return create_factory("main", mainDatasource());
    }

    private DataSource create_datasource(Config config)
    {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl(config.url);
        ds.setUsername(config.username);
        ds.setPassword(config.password);
        ds.setMaxTotal(100);
        ds.setTestWhileIdle(true);
        ds.setTimeBetweenEvictionRunsMillis(10 * 1000);
        ds.setMinEvictableIdleTimeMillis(20 * 1000);
        ds.setRemoveAbandonedOnBorrow(true);
        ds.setRemoveAbandonedTimeout(180);
        return ds;
    }

    private LocalContainerEntityManagerFactoryBean create_factory(
            String persistence_unit_name, DataSource datasource)
    {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

        factory.setPersistenceUnitName(persistence_unit_name);
        factory.setDataSource(datasource);

        HibernateJpaVendorAdapter vendor = new HibernateJpaVendorAdapter();
        vendor.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
        vendor.setGenerateDdl(false);
        vendor.setShowSql(true);
        factory.setJpaVendorAdapter(vendor);

        Properties props = new Properties();
        props.put("hibernate.format_sql", "true");
        props.put("hibernate.hbm2ddl.auto", "validate");
        factory.setJpaProperties(props);

        return factory;
    }
}
